package frame.PayDetail;

import MyBatis.MyBatislianjian;
import frame.GuanliPanel;
import org.apache.ibatis.session.SqlSession;
import org.example.mapper.PayDetailMapper;
import org.example.pojo.PayDetail;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

public class PayDetailPanel extends JInternalFrame {
    private JTable table;
    private DefaultTableModel tableModel;
    private JLabel lblPayDetailCount; // 采购明细记录数量标签
    private JLabel lblTotalQuantity; // 总数量标签
    private JLabel lblTotalAmount; // 总金额标签
    private SqlSession sqlSession = MyBatislianjian.getSqlSession();
    private PayDetailMapper payDetailMapper = sqlSession.getMapper(PayDetailMapper.class);

    public PayDetailPanel() {
        super("采购明细管理界面", true, true, true, true);
        this.setLayout(new BorderLayout());
        this.setSize(800, 600);

        // Initialize JTable
        table = new JTable() {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // Set cells non-editable
            }
        };
        table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); // Enable multiple selection

        // Initialize table data
        initializeTableData();

        // Add table and scroll pane to center
        JScrollPane scrollPane = new JScrollPane(table);
        this.add(scrollPane, BorderLayout.CENTER);

        // Button panel at the bottom
        JPanel buttonPanel = new JPanel(new BorderLayout()); // Use BorderLayout for button panel
        this.add(buttonPanel, BorderLayout.SOUTH);

        // Labels for count, total quantity, and total amount
        lblPayDetailCount = new JLabel("采购明细记录数量: " + tableModel.getRowCount());
        lblPayDetailCount.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));
        buttonPanel.add(lblPayDetailCount, BorderLayout.WEST); // Align to the left

        // Panel for buttons, using FlowLayout and centered alignment
        JPanel buttonCenterPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        buttonPanel.add(buttonCenterPanel, BorderLayout.CENTER);

        // Add buttons: Add, Edit, Delete, Query, Export CSV
        JButton addButton = new JButton("添加");
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                GuanliPanel.setContent(new PayDetailAdd()); // Placeholder for your add functionality
            }
        });
        buttonCenterPanel.add(addButton);

        JButton editButton = new JButton("修改");
        editButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(PayDetailPanel.this, "直接在表格中编辑你想要修改的内容，然后点击确定修改", "提示", JOptionPane.WARNING_MESSAGE);
                GuanliPanel.setContent(new PayDetailupdate()); // Placeholder for your edit functionality
            }
        });
        buttonCenterPanel.add(editButton);

        JButton deleteButton = new JButton("删除");
        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // Implement delete logic
                int[] selectedRows = table.getSelectedRows();
                if (selectedRows.length == 0) {
                    JOptionPane.showMessageDialog(PayDetailPanel.this, "请选择要删除的采购明细记录！", "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                Integer[] pdids = new Integer[selectedRows.length];
                for (int i = 0; i < selectedRows.length; i++) {
                    pdids[i] = (Integer) tableModel.getValueAt(selectedRows[i], 0);
                }

                int res = JOptionPane.showConfirmDialog(PayDetailPanel.this, "是否确认要删除当前选中的数据？删除后数据无法找回，自己承担后果", "确认", JOptionPane.YES_NO_OPTION);
                if (res == JOptionPane.YES_OPTION) {
                    payDetailMapper.deletePayDetail(pdids);
                    sqlSession.commit();
                }

                refreshTableData();
            }
        });
        buttonCenterPanel.add(deleteButton);

        JButton queryButton = new JButton("查询");
        queryButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                GuanliPanel.setContent(new PayDetailselect()); // Placeholder for your query functionality
            }
        });
        buttonCenterPanel.add(queryButton);

        JButton exportButton = new JButton("导出CSV文件");
        exportButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    exportToCSV(); // Export to CSV functionality
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
        });
        buttonCenterPanel.add(exportButton);

        // Add export button to the east of button panel
        buttonPanel.add(exportButton, BorderLayout.EAST);

        // Update labels and data
        updateTotalQuantityLabel(0); // Initialize to 0
        updateTotalAmountLabel(0.0); // Initialize to 0.0
    }

    private void initializeTableData() {
        Object[] columnNames = {"采购明细号", "采购清单号", "商品编号", "采购数量", "商品单价", "商品总价", "备注"};
        List<PayDetail> payDetails = payDetailMapper.selectAll();

        Object[][] data = new Object[payDetails.size()][columnNames.length];
        int totalQuantity = 0;
        double totalAmount = 0.0;
        for (int i = 0; i < payDetails.size(); i++) {
            PayDetail payDetail = payDetails.get(i);
            data[i][0] = payDetail.getPDid();
            data[i][1] = payDetail.getPid();
            data[i][2] = payDetail.getGid();
            data[i][3] = payDetail.getPcount();
            data[i][4] = payDetail.getGpay();
            data[i][5] = payDetail.getTotal();
            data[i][6] = payDetail.getOther();

            totalQuantity += payDetail.getPcount();
            totalAmount += payDetail.getTotal();
        }

        tableModel = new DefaultTableModel(data, columnNames);
        table.setModel(tableModel);

        updatePayDetailCountLabel();
        updateTotalQuantityLabel(totalQuantity);
        updateTotalAmountLabel(totalAmount);
    }

    private void refreshTableData() {
        List<PayDetail> payDetails = payDetailMapper.selectAll();

        tableModel.setRowCount(0);

        int totalQuantity = 0;
        double totalAmount = 0.0;
        for (PayDetail payDetail : payDetails) {
            tableModel.addRow(new Object[]{
                    payDetail.getPDid(),
                    payDetail.getPid(),
                    payDetail.getGid(),
                    payDetail.getPcount(),
                    payDetail.getGpay(),
                    payDetail.getTotal(),
                    payDetail.getOther()
            });

            totalQuantity += payDetail.getPcount();
            totalAmount += payDetail.getTotal();
        }

        updatePayDetailCountLabel();
        updateTotalQuantityLabel(totalQuantity);
        updateTotalAmountLabel(totalAmount);
    }

    private void updatePayDetailCountLabel() {
        if (lblPayDetailCount != null) {
            lblPayDetailCount.setText("采购明细记录数量: " + tableModel.getRowCount());
        }
    }

    private void updateTotalQuantityLabel(int totalQuantity) {
        if (lblTotalQuantity != null) {
            lblTotalQuantity.setText("总数量: " + totalQuantity);
        }
    }

    private void updateTotalAmountLabel(double totalAmount) {
        if (lblTotalAmount != null) {
            lblTotalAmount.setText("总金额: " + totalAmount);
        }
    }

   private void exportToCSV() throws IOException {
        // 提示用户输入文件名
        String suggestedFileName = JOptionPane.showInputDialog(this, "请输入要导出的文件名（不包含扩展名.csv）:");

        if (suggestedFileName == null || suggestedFileName.trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "文件名不能为空！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 设置导出文件的目录为绝对路径（例如：C:/Users/冉前辉/Desktop）
        File defaultDir = new File("C:/Users/冉前辉/Desktop");

        // 构造完整的文件名，确保以用户输入的文件名开头，添加 .csv 扩展名
        String fileName = suggestedFileName.trim() + ".csv";
        File fileToSave = new File(defaultDir, fileName);

        try (FileWriter fw = new FileWriter(fileToSave)) {
            // 写入表头
            for (int i = 0; i < tableModel.getColumnCount(); i++) {
                fw.append(tableModel.getColumnName(i));
                if (i < tableModel.getColumnCount() - 1) {
                    fw.append(",");
                } else {
                    fw.append("\n");
                }
            }

            // 写入数据
            for (int row = 0; row < tableModel.getRowCount(); row++) {
                for (int col = 0; col < tableModel.getColumnCount(); col++) {
                    fw.append(String.valueOf(tableModel.getValueAt(row, col)));
                    if (col < tableModel.getColumnCount() - 1) {
                        fw.append(",");
                    } else {
                        fw.append("\n");
                    }
                }
            }

            JOptionPane.showMessageDialog(this, "CSV文件已成功导出至:\n" + fileToSave.getAbsolutePath(), "导出成功", JOptionPane.INFORMATION_MESSAGE);
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, "导出CSV文件时发生错误：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

}
